//
//  ComposeViewController.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/7/8.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {
    
    
    /// 懒加载表情控制器
    private lazy var emotiocnVC:EmoticonViewController = EmoticonViewController { [unowned self] (emoticon) in
        //这里会造成循环引用
        self.msgTextView.insertEmoticon(emoticon: emoticon)
    }
    
    /// 懒加载图片选择器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    
    /// 保存tolbar底部的约束
    var tolbarBottomCons: NSLayoutConstraint?
    
    /// 保存photoSelector的高度约束
    var photoViewHeightCons: NSLayoutConstraint?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        //0.监听键盘的出现和消失
        NotificationCenter.default.addObserver(self, selector: #selector(keboardChang(notiy:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //添加表情控制器
        addChildViewController(emotiocnVC)
        addChildViewController(photoSelectorVC)
        
        //1.初始化导航条
        setupUI()
        
        //2.初始化消息View
        setupMsgView()
        
        //3.初始化工具条
        setupTolBar()
        
        //4.初始化图片选择器
        setupPhotoView()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if photoViewHeightCons?.constant == 0 {
            msgTextView.becomeFirstResponder()
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //退出的时候取消键盘
        msgTextView.resignFirstResponder()
    }
    /// 初始化导航条
    func setupUI() -> Void {
        
        //1.添加导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelSendWeiBoMsg))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.plain, target: self, action: #selector(sendWeiBoMsg))
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        // 2.添加中间视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
        let label1 = UILabel.creatLbale(color: UIColor.black, fontSize: 15)
        label1.text = "发送微博"
        label1.translatesAutoresizingMaskIntoConstraints = false
        label1.sizeToFit()
        titleView.addSubview(label1)
        
        let label2 = UILabel.creatLbale(color: UIColor.darkGray, fontSize: 13)
        label2.text = UserAccess.loadAccount()?.screen_name
        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.sizeToFit()
        titleView.addSubview(label2)
        
        titleView.addConstraint(NSLayoutConstraint.init(item: label1, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: titleView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0))
        titleView.addConstraint(NSLayoutConstraint.init(item: label1, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: titleView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0))
        
        titleView.addConstraint(NSLayoutConstraint.init(item: label2, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: titleView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0))
        titleView.addConstraint(NSLayoutConstraint.init(item: label2, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: titleView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0))
        
        navigationItem.titleView = titleView

    }
    
    /// 初始化消息View
    func setupMsgView() -> Void {
        //1.添加子控件
        msgTextView.delegate = self
        msgTextView.alwaysBounceVertical = true//始终允许可以垂直方向弹跳
        msgTextView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag//设置向下拖拽TextView时键盘消失
        view.addSubview(msgTextView)
        msgTextView.addSubview(placeholderLable)
        //2.布局子控件
        view.addConstraint(NSLayoutConstraint.init(item: msgTextView, attribute: NSLayoutAttribute.top, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint.init(item: msgTextView, attribute: NSLayoutAttribute.bottom, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint.init(item: msgTextView, attribute: NSLayoutAttribute.left, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint.init(item: msgTextView, attribute: NSLayoutAttribute.right, relatedBy: .equal, toItem: view, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0))
        
        var cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[placeholderLable]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["placeholderLable":placeholderLable])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-8-[placeholderLable]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["placeholderLable":placeholderLable])
        msgTextView.addConstraints(cons)
        
    }
    
    /// 初始化工具条
    func setupTolBar() -> Void {
        view.addSubview(toolBar)
        view.addSubview(tipLable)
        
        var cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["toolBar":toolBar])
        //设置控件垂直方向高度为44
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[toolBar(44)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["toolBar":toolBar])
        tolbarBottomCons = NSLayoutConstraint.init(item: toolBar, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
        cons.append(tolbarBottomCons!)
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[tipLable]-10-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["tipLable":tipLable])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[tipLable]-10-[toolBar]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["tipLable":tipLable,"toolBar":toolBar])
        
        view.addConstraints(cons)
        
    }
    
    /// 初始化图片选择器
    func setupPhotoView() -> Void {
        //1.添加子控件
        photoSelectorVC.view.translatesAutoresizingMaskIntoConstraints = false
        view.insertSubview(photoSelectorVC.view, belowSubview: toolBar)
        
        //2.布局子控件
        var cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[photoView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["photoView":photoSelectorVC.view])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:[photoView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["photoView":photoSelectorVC.view])
        photoViewHeightCons = NSLayoutConstraint.init(item: photoSelectorVC.view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 0)
        cons.append(photoViewHeightCons!)
        
        view.addConstraints(cons)
    }
    
    /// 监听键盘frame的改变
    ///
    /// - Parameter notiy: <#notiy description#>
    func keboardChang(notiy: Notification) -> Void {
        //1.取得键盘frame改变后的值
        let rect = notiy.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
       
        //2.修改tolbar的底部约束
        tolbarBottomCons?.constant = -(UIScreen.main.bounds.height - rect.origin.y)
        
        //3.更新视图(强制更新布局)
        toolBar.layoutIfNeeded()
    }
    
    /// 取消微博
    func cancelSendWeiBoMsg() -> Void {
        dismiss(animated: true, completion: nil)
    }
    
    /// 发送微博
    func sendWeiBoMsg() -> Void {
        
        if photoSelectorVC.pictreImages.count > 0 {
            //图片微博
            let path = "2/statuses/upload.json"
            let params = ["access_token" : UserAccess.loadAccount()!.access_token! , "status" : msgTextView.emoticonAttributedText()]
            let image = photoSelectorVC.pictreImages.last!
            NetworkTools.shareNetworkTools().post(path, parameters: params, constructingBodyWith: { (formData) in
                
                let data = UIImagePNGRepresentation(image)!
                /**
                 1. 文件的二进制数据
                 2. 服务器的字段名，后端接口会提供
                 3. 保存在服务器的文件名，有些服务器可以随便写(接收到请求后，会做后续处理)
                 4. mimeType，告诉服务器文件类型，application/octect-stream
                 */
                formData.appendPart(withFileData: data, name: "pic", fileName: "hello", mimeType: "application/octect-stream")
            }, progress: { (_) in
                
            }, success: { (_, JSON) in
                SVProgressHUD.showSuccess(withStatus: "发送微博成功!")
            }, failure: { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发送微博失败!")
            })
        }else {
            //文本微博
            let path = "2/statuses/update.json"//https://api.weibo.com/2/statuses/share.json
            let params = ["access_token":UserAccess.loadAccount()?.access_token! , "status": msgTextView.emoticonAttributedText()]
            NetworkTools.shareNetworkTools().post(path, parameters: params, progress: { (Progress) in
                
            }, success: { (_, json) in
                print(json ?? 99)
                SVProgressHUD.showSuccess(withStatus: "发送微博成功!")
                self.dismiss(animated: true, completion: nil)
            }) { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发送微博失败!")
            }
        }
    }
    
    /// 工具条的点击事件
    ///
    /// - Parameter btn: <#btn description#>
    func toolBarItemClick(btn: UIBarButtonItem) -> Void {
        print(#function)
        //结论:如果是系统键盘textView.inputView属性是nil,如果不是系统键盘则有值
        //print(msgTextView.inputView)
        
        switch btn.tag {
        case 1:
            //收起键盘
            msgTextView.resignFirstResponder()
            
            //改变高度约束
            photoViewHeightCons?.constant = UIScreen.main.bounds.height * 0.6
            
            //刷新视图
            photoSelectorVC.view.layoutIfNeeded()
            
        case 2:
            print("")
            
        case 3:
            print("")
            
        case 4:
            //1.关闭系统键盘
            msgTextView.resignFirstResponder()
            
            //2.设置自己的键盘
            msgTextView.inputView = (msgTextView.inputView) == nil ? emotiocnVC.view : nil
            
            msgTextView.becomeFirstResponder()
        case 5:
            print("")
            
        default:
            break
        }
    }
    //MARK: --懒加载
    
    //textView
    fileprivate lazy var msgTextView: UITextView = {
        let tt = UITextView()
        tt.font = UIFont.systemFont(ofSize: 20)
        tt.translatesAutoresizingMaskIntoConstraints = false
        tt.textColor = UIColor(red: 204/255.0, green: 204/255.0, blue: 204/255.0, alpha: 1.0)
        
        return tt
    }()
    
    //标签lable
    fileprivate lazy var placeholderLable: UILabel = {
        let tt = UILabel()
        tt.text = "分享新鲜事..."
        tt.translatesAutoresizingMaskIntoConstraints = false
        tt.font = UIFont.systemFont(ofSize: 20)
        tt.textColor = UIColor(white: 0.5, alpha: 1.0)
        
        return tt
    }()
    
    //工具条
    private lazy var toolBar: UIToolbar = {
        
        let toolBar = UIToolbar()
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        var items = [UIBarButtonItem]()
        let titleNames = ["compose_toolbar_picture","compose_mentionbutton_background","compose_trendbutton_background","compose_emoticonbutton_background","compose_addbutton_background"]
        var itemTag = 0
        
        for imageName in titleNames {
            itemTag += 1
            let barButton = UIBarButtonItem(imageName: imageName, tag: itemTag, target: self, action: #selector(toolBarItemClick(btn:)))
            items.append(barButton)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
        return toolBar;
    }()
    
    //字数显示lable
    fileprivate lazy var tipLable: UILabel = {
        let lable = UILabel()
        lable.translatesAutoresizingMaskIntoConstraints = false
        
        return lable
    }()
    
}
private let maxLength = 140
extension ComposeViewController:UITextViewDelegate {

    
    func textViewDidChangeSelection(_ textView: UITextView) {
        placeholderLable.isHidden = msgTextView.hasText //返回textView有没有内容
        navigationItem.rightBarButtonItem?.isEnabled = msgTextView.hasText
        
        //设置字数提醒
        let count = msgTextView.emoticonAttributedText().characters.count
        let res = maxLength - count
        tipLable.text = res == maxLength ? "" : "\(res)"
        tipLable.textColor = res > 0 ? UIColor.darkGray : UIColor.red
    }
}





